package handler

import (
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"net/http"
	"zk12.27/api/request"
	"zk12.27/glodal"
	"zk12.27/internal/model"
)

func MessageAdd(c *gin.Context) {
	var req request.MessageAdd
	err := c.ShouldBind(&req)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  "验证失败",
			"data": err.Error(),
		})
		return
	}
	message := model.Message{
		MessageUserId:  req.MessageUserId,
		MessageContent: req.MessageContent,
		ReceiveLiveId:  req.ReceiveLiveId,
	}
	err = glodal.DB.Create(&message).Error
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  "直播间创建失败",
			"data": nil,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "成功",
		"data": message.ID,
	})
}

func MessageList(c *gin.Context) {
	var req request.MessageList
	err := c.ShouldBind(&req)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  "验证失败",
			"data": err.Error(),
		})
		return
	}
	var msg []model.Message
	err = glodal.DB.Where("receive_live_id = ?", req.ReceiveLiveId).Find(&msg).Error
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 200,
			"msg":  "该直播间不存在",
			"data": nil,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "成功",
		"data": msg,
	})
}

func MessageUpdate(c *gin.Context) {
	var req request.MessageUpdate
	err := c.ShouldBind(&req)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  "验证失败",
			"data": err.Error(),
		})
		return
	}
	msg := model.Message{
		Model:          gorm.Model{ID: req.MessageId},
		MessageContent: req.MessageContent,
	}
	err = glodal.DB.Updates(&msg).Error
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  "评论内容修改失败",
			"data": nil,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "评论内容修改成功",
		"data": msg,
	})
}

func MessageDelete(c *gin.Context) {
	var req request.MessageDelete
	err := c.ShouldBind(&req)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  "验证失败",
			"data": err.Error(),
		})
		return
	}
	var msg model.Message
	err = glodal.DB.Where("id = ?", req.MessageId).First(&msg).Error
	if msg.ID == 0 {
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  "该直播间不存在",
			"data": nil,
		})
		return
	}
	err = glodal.DB.Delete(&msg).Error
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  "直播间删除失败",
			"data": nil,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "成功",
		"data": msg.ID,
	})
}
